	var CLIENTREFRESH= 10000;
	var PORT= 8989;
	var http= require("http");
	var sys= require("util");
	var staticServer= require("node-static");
	var serverPath= "c:/users/";
	
	//debugging node.js allegedly sucks, so lets write frequently out to console
	//also have sys.puts() to do that
	function gecho(msg){
		console.log(msg);
	};
	//
	var file = new(staticServer.Server)('.', { cache: 7200, headers: {'X-Hello':'World!'} });
	//setup the server 
	var server= http.createServer(function(request, response){
		request.addListener('end', function(){
			file.serve(request, response, function(err, res){
				if (err) { 
	                sys.error(">> Error serving " + request.url + " - " + err.message);
	                response.writeHead(err.status, err.headers);
	                response.end("<h1>404</h1><p>Page Not Found</p>");
	            } else { 
	                sys.puts(">> " + request.url + " - " + res.message);
	            }
			});
		});
	});
	server.listen (PORT);
	gecho("Listening on localhost: " + PORT);


	//setup now.js	
	var nowjs = require("now");
	var everyone = nowjs.initialize(server);
	var refresh;
	
	nowjs.on('connect', function(){
	  	this.now.room = "room 1";
	  	this.now.name= addTrader(this.now.name, this.user.clientId);
		this.now.credit= setCredit();
	  	nowjs.getGroup(this.now.room).addUser(this.user.clientId);
	  	this.now.exeOnConnect(); //is there something i need to execute on client??
	});
	
	
	nowjs.on('disconnect', function(){
	  	removeTrader(findTraderById(this.user.clientId))
	  	console.log("Left: " + this.now.name);
	});
	
	everyone.now.changeRoom = function(newRoom){
	  	nowjs.getGroup(this.now.room).removeUser(this.user.clientId);
	  	nowjs.getGroup(newRoom).addUser(this.user.clientId);
	  	this.now.room = newRoom;
	  	this.now.receiveMessage("SERVER", "You're now in " + this.now.room);
	}
	
	everyone.now.distributeMessage = function(message){
	  	nowjs.getGroup(this.now.room).now.receiveMessage(this.now.name, message);
	};
	
	//serves all users at once, also gets called everytime any user buys or sells 
	everyone.now.sendStuff = function(obj){
		//notify the market of the sale
		if(obj != undefined){
			console.log("-------------- " + obj.ID + obj.units + obj.act);
			equitieExchange(obj.ID, obj.units, obj.act);
		}
		//regular request initiated by the interval
		nowjs.getGroup(this.now.room).now.receiveStuff(getGlobal());
	};
		
	everyone.now.initGlobalModel= function(){
		//returns an object for client side initialization
		this.now.setGlobalModel(getGlobal());
	};
	everyone.now.commitPortf= function(obj){
		//uppdates the trader portfolio info
		appendToTrader(this.now.name, obj);
	};
	
	everyone.now.sendResults= function(obj){
		//return the sorted array of traders
		sortTraders();
		nowjs.getGroup(this.now.room).now.recieveResult(traders);
		
	};
	
	
	/**
	 * in hope of keeping this modular and loosely coupled
	 * we seperate buissnes logic from now.js
	 * Everything now.js returns it gets from these variables and objects/functions below
	 * Everything now.js edits "on the global market" it does through these objects/functions 
	 * and then returns values back to GUI using it´s own functions
	 */


	//TODO: make into an object	that contains the whole market stuff
	var MAXFLUX= 20;				//maximum random market flux
	var MARKETTIME= 5;				//time for market countdown in minutes		
	var INITCREDIT= 10000;			//credit each starts with
	
	var time;						//minutes countdown
	var marketMsg= "hide";				//message used for stuff
	var marketOpen;					//true or false if market is open
	var interv= 60000;				//interval to execute countdown by (release 60000= 1 min) 
	var timeCountDown;				//holds the interval object
	var market;						//holds the array of stock objects, perhaps this should be an obj with methods that can do stuff to inidvidual Equity
	var lastFiveExc= new Array;		//Last market manips
	var traders= new Array;			//holds the array of traders
	
	
	//equity object
	function Equity(id, name, currPr, startPr, lastMove, dir){
		this.ID= id;
		this.name= name;
		this.currPr= currPr;
		this.startPr= startPr;
		this.lastMove= lastMove;
		this.dir= dir;
		this.setCurrent= function(prize){
			this.currPr= prize;
		}
	};
	function initMarket(){
		//stub for implementing some basic stock prices
		//guess this is not getting any more clever for the time being
		market= new Array;
		market.push(new Equity("USD", "US Dollar", 50, 50, 0, null));
		market.push(new Equity("DKK", "Danish Krona", 20, 20, 0, null));
		market.push(new Equity("SKK", "Swedish Krona", 5, 5, 0, null));
		market.push(new Equity("NKK", "Norwegina Krona", 10, 10, 0, null));
		market.push(new Equity("EUR", "EURO", 100, 100 ,0, null));		
	};
	function getGlobal(){
		//might need to filter the traders obj before returning it
		//since we are using multipe viewmodels on one page , some "namespace" could be clever
		var jsObj= { "equities":market
	  				,"remTime":time
	  				,"msg": marketMsg
	  				,"marketOpen": marketOpen
	  				,"traders":traders
	  	};
	  	return jsObj;
	}
	function setCredit(){
		return INITCREDIT;
	};
	
	//initialies exchange, starts timer, sets up stocks and so on
	function openExchange(){
		gecho("-----------------");
		gecho("Opening Exchange");
		gecho("-----------------");
		marketOpen= true;
		marketMsg= " ";
		time= MARKETTIME;
		initMarket();
		timeCountDown= setInterval(function(){
			if(time > 0){
				time= time -1;
				//gecho("decrementing " + time);
				if((time%2) == 0 && time > 0){
					//manipulate the market
					kaupThinking();
				}
			}
			else{
				//think this is not getin cleared???
				clearInterval(timeCountDown);
				closeExchange();
				
			}
		},interv) //made a change
	}

	
			
	//close exchange 
	function closeExchange(){
		gecho("-----------------");
		gecho("Closing Exchange");
		gecho("-----------------");
		marketOpen= false;
		marketMsg= "SomeBody won!!!! Calculating"
		sortTraders();
	};
	
	//trader functions are somwhat buggy, need refactor this mechanism
	
	function sortTraders(){
		var cmp= function(a,b){
			  if(a.total < b.total)
			     return -1;
			  if (a.total > b.total)
			    return 1;
			  return 0;
		}
		traders.sort(cmp);
		traders.reverse();
	}
	
	//adds a trader to the list of traders
	function addTrader(name, userId){
		if(traders.length === 0){
			console.log("traders Lengt: " + traders.length)
			openExchange();
		}
		var exists= findTraderByName(name);
	  	if(exists < 0 || traders.length === 0){
	  		gecho("Trader:" +  name);
	  		traders.push({"name":name, "userId":userId});
  			return name;
	  	}
	  	else{
	  		//should check again but...neeh!
	  		while(exists >= 0){
	  			gecho("Trader: already there");
	  			name= traders[exists].name + getRandom(0,100);
	  			exists= findTraderByName(name);
	  		}
	  		traders.push({"name":name, "userId":userId});
  			return name;
	  	}
	};
	
	//remove a trader from the list of traders logged on
	//not very efficient but will do for now
	function removeTrader(id){
		var temp = new Array;
		for(i=0;i<traders.length;i++){
			if(i != id)
				temp.push(traders.pop());
			else
				traders.pop();
		}
		temp.reverse();
		traders= temp;
		gecho("Removed " +id);
	};
	//appends an object to a given trader
	function appendToTrader(name, obj){
		tid= findTraderByName(name);
		traders[tid].total= obj.total;
		traders[tid].portfolio= obj;
	}
	
	function findTraderById(id){
		gecho("findByID: " + id);
		for(i=0;i<traders.length;i++){
			if(traders[i].userId === id){
				gecho("findByName:FOUND " + i);
				return i;
			}
		}
		return -1;
		
	};
	
	function findTraderByName(name){
		
		gecho("findtraderByName: " + name);
		for(i=0;i<traders.length;i++){
			if(traders[i].name === name){
				gecho("findByName:FOUND " + i);
				return i;
			}
		}
		return -1;
	
	};
		
	//random market manipulation
	function kaupThinking(){
		var eq= getRandom(0,(market.length-1));
		var perc= getRandom(1,MAXFLUX);
		var direction= (getRandom(0,1)== 0) ? 'UP' : 'DW';
		//gecho("kaupThinking-> " + eq.toString() + " " +  perc.toString() + " " + direction);
		changePrice(eq,perc,direction);
	};
	
	//change the prize of a stock on the market
	function changePrice(stock, perc ,direction){
		console.log("-change- " + stock + perc + direction);
		var eq= market[stock];
		var ch= eq.currPr * (perc/100);
		if(direction === 'UP')
			eq.currPr= roundNumber((eq.currPr + ch),2);
		else
			eq.currPr= roundNumber((eq.currPr + ch),2);
		eq.lastMove= roundNumber(perc,3);
		eq.direction= direction;
		market[stock]= eq;
	}
	
	//generate a random num within bounds
	function getRandom(min, max){
		var randVal = min+(Math.random()*(max-min));
  		return Math.round(randVal);
	};
	
	//roundng
	function roundNumber(num, dec) {
		return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	}
	
	//returns the index of a stock with a given ID 
	function findEqById(id){
		for(i=0;i<market.length;i++){
			if(market[i].ID === id){
				return i;
			}
		}
		return -1
	};
	
	//evaluates the current market state and returns a tendencie 'UP'/'DW' and changes impact on scale 1-3
	//...for fun
	function marketMomentum(){
		var rslt= {'dir':"", 'avgFlux':0 };
		var countUp=0;
		var countDw=0;
		var avgFlux= 0;
		for(i=0;i<market.length;i++){
			if(market[i].dir === 'UP')
				countUp++;
			else if(market[i].dir === 'DW')
				countDw++;
			avgFlux+= market[i].lastMove;				
		}
		if(countUp < countDw)
			rslt.dir= 'DW';
		else
			rslt.dir= 'UP';
		if(market.length > 0)
			avgFlux= avgFlux/market.length;
		//markteet flux on the scale 1-3
		var steps= roundNumber(MAXFLUX / 3)
		if(avgFlux <= steps)
			rslt.avgFlux= 1;
		else if(avgFlux <= 2*steps)
			rslt.avgFlux= 2;	
		else if(avgFlux <= 3*steps)
			rslt.avgFlux= 3;
		return rslt;
	}
	////manipulate an item in the trader arry and change it prize 
	//just for the sake of tryin and because its fun...
	function equitieExchange(stockId, units, act){
		console.log("--equitie--- " + stockId + units + act);
		var mom= marketMomentum();
		var id= findEqById(stockId);
		var lastMove= market[id].lastMove;
		var lastDir= market[id].dir;
		var dir, perc; 
		dirConst= 1;
		if(lastDir === 'UP' && mom.dir === 'UP' && act === 'buy') dirConst= 40;
		if(lastDir === 'UP' && mom.dir === 'UP' && act === 'sell') dirConst= 30;
		if(lastDir === 'UP' && mom.dir === 'DW' && act === 'buy') dirConst= 20;
		if(lastDir === 'DW' && mom.dir === 'UP' && act === 'sell') dirConst= 20;
		if(lastDir === 'DW' && mom.dir === 'DW' && act === 'buy') dirConst= 30;
		if(lastDir === 'DW' && mom.dir === 'DW' && act === 'sell') dirConst= 40;
		var formula= (((mom.avgFlux*10) + lastMove + dirConst) + (units/100) ); 
		console.log("formula gives : " + formula);
		//SELL
		if(act === 'sell')
			dir= 'DW';
		//BUY
		else if(act === 'buy')
			dir= 'UP';
		changePrice(id, roundNumber(formula,0), dir);
	};
	
	
